package com.dzl.config.database;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;


@Configuration
public class DataSourceConfig {
	@Bean
	@ConfigurationProperties("spring.datasource.druid.master")
	public DataSource masterDataSource(){
		return DruidDataSourceBuilder.create().build();
	}

	@Bean
	public WallFilter wallFilter(WallConfig wallConfig) {
		WallFilter wallFilter = new WallFilter();
		wallFilter.setConfig(wallConfig);
		return wallFilter;
	}

	@Bean
	public WallConfig wallConfig() {
		WallConfig wallConfig = new WallConfig();
		wallConfig.setMultiStatementAllow(true);// 允许一次执行多条语句
		wallConfig.setNoneBaseStatementAllow(true);//允许非基本语句的其他语句
		return wallConfig;
	}

	@Bean
	@ConfigurationProperties("spring.datasource.druid.slave01")
	public DataSource slave1DataSource(){
		return DruidDataSourceBuilder.create().build();
	}

	@Bean
	@Primary
	public DataSource myRoutingDataSource(@Qualifier("masterDataSource") DataSource masterDataSource,
										  @Qualifier("slave1DataSource") DataSource slave1DataSource) {
		Map<Object, Object> targetDataSources = new HashMap<>();
		targetDataSources.put(DBTypeEnum.MASTER, masterDataSource);
		targetDataSources.put(DBTypeEnum.SLAVE1, slave1DataSource);

		MyRoutingDataSource myRoutingDataSource = new MyRoutingDataSource();
		myRoutingDataSource.setDefaultTargetDataSource(masterDataSource);
		myRoutingDataSource.setTargetDataSources(targetDataSources);
		return myRoutingDataSource;
	}
}
